﻿using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Core;
using System.Web;

namespace Yuanlin.Business
{
    public class CompanyProductSearchResult : YuanlinUserControl,
        IReplyConverter<CompanyProductReply, GetListOperation>
    {
        private NameValueCollection formData;
        protected ValuedDropDownList provinceDropDownList;
        protected ValuedDropDownList cityDropDownList;
        protected ValuedDropDownList townDropDownList;
        protected ValuedDropDownList smallTownDropDownList;
        protected ValuedDropDownList parentCategoryDropDownList;
        protected ValuedDropDownList tradeTypeDropDownList;
        protected Repeater list;
        protected Pager pager;
        protected CurrentPage currentPage;
        protected Button btnQty;
        protected Button btnPrice;
        protected Button btnUpdateDate;
        protected Button searchProductButton;
        private int provinceId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.ProvinceId);
        private int cityId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.CityId);
        private int townId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.TownId);
        private int smallTownId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.SmallTownId);
        private int productCategoryId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.ProductCategoryId);
        private string queryText = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.QueryText);
        private int level = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.Level);
        private int area = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.Area);
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);
        private int defaultIndex = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.DefaultIndex);
        private string orderBy = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.OrderBy);
        private string ascStr = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.Asc);
        private EntityList companyProducts;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            if (!Page.IsPostBack && !AjaxManager.IsCallBack)
            {
                if (string.IsNullOrEmpty(orderBy))
                {
                    requestBinders.Add(RequestHelper.BuildGetCompanyProductListRequest(this, productCategoryId, queryText, level, area, tradeType, 1, pager.PageIndex, pager.PageSize));
                }
                else
                {
                    CompanyProductListRequest request = new CompanyProductListRequest();
                    request.PageIndex = pager.PageIndex;
                    request.PageSize = pager.PageSize;
                    request.CategoryId = productCategoryId;
                    request.Title = queryText;
                    request.AreaLevel = level;
                    request.AreaId = area;
                    request.TradeType = tradeType;
                    request.Verify = 1;
                    int asc = string.IsNullOrEmpty(ascStr) ? 0 : Globals.ChangeType<int>(ascStr);
                    requestBinders.Add(RequestHelper.BuildGetCompanyProductListRequest(this, request, orderBy, asc));
                }
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            btnQty.Click += new EventHandler(btnQty_Click);
            btnPrice.Click += new EventHandler(btnPrice_Click);
            btnUpdateDate.Click += new EventHandler(btnUpdateDate_Click);
            searchProductButton.Click += new EventHandler(searchProductButton_Click);
            AjaxManager.Register(this, "Search");
        }

        protected void searchProductButton_Click(object sender, EventArgs e)
        {
            formData = HttpContext.Current.Request.Form;
            ReBindProducts("", "");
        }
        protected void btnQty_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ascStr))
            {
                ascStr = "0";
            }
            else
            {
                ascStr = ascStr == "0" ? "1" : "0";
            }

            formData = HttpContext.Current.Request.Form;
            ReBindProducts("Number", ascStr);
        }
        protected void btnPrice_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ascStr))
            {
                ascStr = "0";
            }
            else
            {
                ascStr = ascStr == "0" ? "1" : "0";
            }
            formData = HttpContext.Current.Request.Form;
            ReBindProducts("Price", ascStr);
        }
        protected void btnUpdateDate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ascStr))
            {
                ascStr = "0";
            }
            else
            {
                ascStr = ascStr == "0" ? "1" : "0";
            }
            formData = HttpContext.Current.Request.Form;
            ReBindProducts("UpdateDate", ascStr);
        }
        private void Bind()
        {
            tradeTypeDropDownList.Items.Add(new ListItem("<请选择>", ""));
            tradeTypeDropDownList.Items.Add(new ListItem("出售花木", "0"));
            tradeTypeDropDownList.Items.Add(new ListItem("求购花木", "2"));
            tradeTypeDropDownList.Items.Add(new ListItem("精品花木", "1"));
            tradeTypeDropDownList.Items.Add(new ListItem("急售花木", "3"));
            tradeTypeDropDownList.Value = tradeType;
            if (defaultIndex > 0)
            {
                tradeTypeDropDownList.Enabled = false;
            }

            AreaListRequest request = new AreaListRequest();
            request.UpAreaId = 0;
            EntityList topCategories = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            EntityList defaultCategories1 = new EntityList();
            EntityList defaultCategories2 = new EntityList();
            EntityList defaultCategories3 = new EntityList();

            Area topCategory = new Area();
            topCategory.Title.Value = "<选择省>";
            topCategory.EntityId.Value = -1;

            Area topCategory1 = new Area();
            topCategory1.Title.Value = "<选择市>";
            topCategory1.EntityId.Value = -1;

            Area topCategory2 = new Area();
            topCategory2.Title.Value = "<选择县>";
            topCategory2.EntityId.Value = -1;

            Area topCategory3 = new Area();
            topCategory3.Title.Value = "<选择乡>";
            topCategory3.EntityId.Value = -1;

            if (provinceId > 0)
            {
                request = new AreaListRequest();
                request.UpAreaId = provinceId;
                defaultCategories1 = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            }
            if (cityId > 0)
            {
                request = new AreaListRequest();
                request.UpAreaId = cityId;
                defaultCategories2 = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            }
            if (townId > 0)
            {
                request = new AreaListRequest();
                request.UpAreaId = townId;
                defaultCategories3 = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            }

            topCategories.Insert(0, topCategory);
            defaultCategories1.Insert(0, topCategory1);
            defaultCategories2.Insert(0, topCategory2);
            defaultCategories3.Insert(0, topCategory3);

            this.provinceDropDownList.DataSource = topCategories;
            this.provinceDropDownList.DataValueField = "EntityId";
            this.provinceDropDownList.DataTextField = "Title";
            this.provinceDropDownList.DataBind();
            this.provinceDropDownList.Value = provinceId.ToString();

            this.cityDropDownList.DataSource = defaultCategories1;
            this.cityDropDownList.DataValueField = "EntityId";
            this.cityDropDownList.DataTextField = "Title";
            this.cityDropDownList.DataBind();
            this.cityDropDownList.Value = cityId.ToString();

            this.townDropDownList.DataSource = defaultCategories2;
            this.townDropDownList.DataValueField = "EntityId";
            this.townDropDownList.DataTextField = "Title";
            this.townDropDownList.DataBind();
            this.townDropDownList.Value = townId.ToString();

            this.smallTownDropDownList.DataSource = defaultCategories3;
            this.smallTownDropDownList.DataValueField = "EntityId";
            this.smallTownDropDownList.DataTextField = "Title";
            this.smallTownDropDownList.DataBind();
            this.smallTownDropDownList.Value = smallTownId.ToString();

            ProductCategoryListRequest request1 = new ProductCategoryListRequest();
            request1.CategoryType = 0;
            EntityList topCategories2 = BusinessManager.GetProductCategoryList(RequestHelper.BuildGetProductCategoryListRequest(request1));
            ProductCategory productCategory = new ProductCategory();
            productCategory.Title.Value = "<请选择>";
            productCategory.EntityId.Value = -1;
            topCategories2.Insert(0, productCategory);
            this.parentCategoryDropDownList.DataSource = topCategories2;
            this.parentCategoryDropDownList.DataValueField = "EntityId";
            this.parentCategoryDropDownList.DataTextField = "Title";
            this.parentCategoryDropDownList.DataBind();
            this.parentCategoryDropDownList.Value = productCategoryId.ToString();
        }
        private void BindProducts()
        {
            list.DataSource = companyProducts;
            list.DataBind();

            if (pager != null && currentPage != null)
            {
                pager.TotalPages = pager.CalculateTotalPages(companyProducts.TotalCount);
                currentPage.TotalRecords = companyProducts.TotalCount;
                currentPage.TotalPages = pager.TotalPages;
                currentPage.PageIndex = pager.PageIndex;
            }
        }
        private void ReBindProducts(string orderBy, string asc)
        {
            int provinceID = 0;
            int cityID = 0;
            int townID = 0;
            int smallTownID = 0;
            int productCategoryID = 0;
            string tradeType = string.Empty;
            int areaID = 0;
            int level = 0;

            if (!string.IsNullOrEmpty(formData[provinceDropDownList.UniqueID]))
            {
                provinceID = int.Parse(formData[provinceDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[cityDropDownList.UniqueID]))
            {
                cityID = int.Parse(formData[cityDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[townDropDownList.UniqueID]))
            {
                townID = int.Parse(formData[townDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[smallTownDropDownList.UniqueID]))
            {
                smallTownID = int.Parse(formData[smallTownDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[this.parentCategoryDropDownList.UniqueID]))
            {
                productCategoryID = int.Parse(formData[this.parentCategoryDropDownList.UniqueID]);
            }

            if (!string.IsNullOrEmpty(formData[this.tradeTypeDropDownList.UniqueID]))
            {
                tradeType = formData[this.tradeTypeDropDownList.UniqueID];
            }

            if (smallTownID > 0)
            {
                areaID = smallTownID;
                level = 4;
            }
            else if (townID > 0)
            {
                areaID = townID;
                level = 3;
            }
            else if (cityID > 0)
            {
                areaID = cityID;
                level = 2;
            }
            else if (provinceID > 0)
            {
                areaID = provinceID;
                level = 1;
            }

            string queryTextStr = string.Empty;
            if (queryText != "-1")
            {
                queryTextStr = queryText;
            }
            HttpContext.Current.Response.Redirect(SiteUrls.Instance().GetCompanyProductSearchResultUrl(areaID, level, productCategoryID, System.Web.HttpUtility.HtmlEncode(tradeType), System.Web.HttpUtility.HtmlEncode(queryTextStr), provinceID, cityID, townID, smallTownID, orderBy, asc));
        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetChildCategories(int parentCategoryID)
        {
            if (parentCategoryID == -1)
            {
                return string.Empty;
            }
            AreaListRequest request = new AreaListRequest();
            request.UpAreaId = parentCategoryID;
            EntityList categories = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));

            if (categories != null && categories.Count > 0)
            {
                string categoryFormat = "{0}:{1}";
                string categoryString = string.Empty;
                foreach (Area category in categories)
                {
                    if (categoryString != string.Empty)
                    {
                        categoryString += ";";
                    }
                    categoryString += string.Format(categoryFormat, category.EntityId.ToString(), category.Title);
                }
                return categoryString;
            }

            return string.Empty;
        }

        #region IReplyConverter<CompanyProductReply,GetListOperation> Members

        public void ConvertReply(CompanyProductReply reply, GetListOperation operation)
        {
            if (reply != null)
            {
                companyProducts = reply.EntityList;
                if (!Page.IsPostBack && !AjaxManager.IsCallBack)
                {
                    Bind();
                    BindProducts();
                }
            }
        }

        #endregion
    }
}

